package com.java.androidmarket.controller;

import com.alibaba.fastjson.JSON;
import com.google.common.collect.Lists;
import com.java.androidmarket.dto.GoodsDTO;
import com.java.androidmarket.dto.order.GetOrderDTO;
import com.java.androidmarket.dto.order.OrderGoodsListDTO;
import com.java.androidmarket.entity.*;
import com.java.androidmarket.service.GoodsService;
import com.java.androidmarket.service.KillStockService;
import com.java.androidmarket.service.StockService;
import com.java.androidmarket.utils.JWTUtils;
import com.java.androidmarket.utils.RedisUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.text.ParseException;
import java.util.*;

/**
 * description:
 * author:张腾
 * date:2021-04-21
 */

@RestController
@CrossOrigin
@RequestMapping("goods")
@Api(tags = "商品模块")
public class GoodsController {

    @Autowired
    private GoodsService goodsService;
    @Autowired
    private StockService stockService;
    @Autowired
    private KillStockService killStockService;
    @Resource
    private RedisUtils redisUtils;


    @GetMapping("/getHot")
    @ApiOperation(value = "热门商品推荐")
    public Result selectForHomePage(){
        List<Goods> goods = null;

        int num = redisUtils.hmKeysNum("goods");
        if (num>=100){
            System.out.println("redis查找商品");

            Set<String> list = new HashSet<>();
            List<String> keys = Lists.newArrayList(redisUtils.hmGetKeys("goods"));
            int i = new Random().nextInt(keys.size() - 20);
            keys = keys.subList(i,i+20);
            for (String hmKey : keys) {
                list.add(hmKey);
            }
            goods = redisUtils.hmMutiGet("goods",list);

        }else {
            System.out.println("数据库中查找商品");
            goods = goodsService.selectForHomePage();
            Map<String,Object> map = new HashMap<>();
            for (int i = 0; i < goods.size(); i++) {
                Goods good = JSON.parseObject(JSON.toJSONString(goods.get(i)), Goods.class);
                String goodsId = String.valueOf(good.getGoodsId());
                if (!redisUtils.hmExist("goods",goodsId)){
                    map.put(goodsId,good);
                }
            }
            redisUtils.hmMutiSet("goods",map);
        }

        return Result.success(goods,goods.size());
    }

    @GetMapping("/getDetail")
    @ApiOperation(value = "商品详情", notes = "为商品详情页面提供数据")
    @ApiImplicitParam(dataType = "int",name = "goodsId", value = "商品ID")
    public Result getGoodsDetails(int goodsId) throws ParseException {

        Goods goods = null;
        //获取商品信息
        if (redisUtils.hmExist("goods",String.valueOf(goodsId))) {
            goods = (Goods) redisUtils.hmGet("goods",String.valueOf(goodsId));
            System.out.println("redis查找商品");
        }else{
            System.out.println("数据库查找商品");
            goods = goodsService.getGoodsDetails(goodsId);
            if (goods==null){
                return Result.error("查无此商品");
            }
            redisUtils.hmSet("goods",String.valueOf(goodsId),goods);
        }


        //存入用户浏览记录
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        if (request.getHeader("Token")!=null) {
            String token = request.getHeader("Token");
            String userId = JWTUtils.DecodedGetID(token);
            Set list = redisUtils.zGet("Recent_browse_list:" + userId);
            if (list.size()>=30){
                redisUtils.zDelOne("Recent_browse_list:" + userId);
            }
            redisUtils.zSet("Recent_browse_list:"+userId,goods,System.currentTimeMillis());
        }

        //如果是秒杀商品则单独查找库存信息，如果是普通商品则直接返回剩余库存
        if (goods.getIsKill()==0){
            int realStock = stockService.getStock(goodsId);
            GoodsDTO goodsDTO = new GoodsDTO();
            goodsDTO.setGoodsId(goods.getGoodsId()).setGoodsName(goods.getGoodsName()).setGoodsCategory(goods.getGoodsCategory()).setDealCount(goods.getDealCount()).
                    setGoodsPic(goods.getGoodsPic()).setGoodsPrice(goods.getGoodsPrice()).setGoodsLocation(goods.getGoodsLocation()).
                    setIsKill(goods.getIsKill());
            goodsDTO.setRealStock(realStock);
            return Result.success(goodsDTO,1);
        }else{
            GoodsDTO goodsDTO = new GoodsDTO();
            goodsDTO.setGoodsId(goods.getGoodsId()).setGoodsName(goods.getGoodsName()).setGoodsCategory(goods.getGoodsCategory()).setDealCount(-1).
                    setGoodsPic(goods.getGoodsPic()).setGoodsPrice(goods.getGoodsPrice()).setGoodsLocation(goods.getGoodsLocation()).
                    setIsKill(goods.getIsKill());
            goodsDTO.setRealStock(-1);

            HashMap<String, Object> map = new HashMap<>();
            map.put("goods",goods);
            map.put("timeToKill",goodsService.checkKillTime());
            return Result.success(map,1);
        }

    }

    @GetMapping("/getByCate")
    @ApiOperation(value = "商品分类" ,notes = "根据商品分类获取不同的商品")
    @ApiImplicitParams({
            @ApiImplicitParam(dataType = "String", name = "goodsCategory", value = "商品分类"),
            @ApiImplicitParam(dataType = "int", name = "goodsPage", value = "商品所属页面")
    })
    public Result selectByCate(@RequestParam(name = "goodsCategory") String goodsCategory, @RequestParam(name = "goodsPage") int goodsPage){

        List<Goods> goods = goodsService.selectByCate(goodsCategory, goodsPage);

        return Result.success(goods,goods.size());
    }

    @GetMapping("search")
    @ApiOperation(value = "商品搜索" , notes = "根据搜索信息模糊查询name和category")
    @ApiImplicitParam(dataType = "String", name = "search", value = "搜索内容")
    public Result search(String search){

        List<Goods> goods = goodsService.search(search);

        return Result.success(goods, goods.size());
    }


    @GetMapping("getKill")
    @ApiOperation(value = "获取秒杀商品", notes = "获取秒杀商品列表")
    public Result getKillGoods() throws ParseException {

//        if (redisUtils.exists("KillGoods")){
//            redisUtils.get("KillGoods")
//        }
        List<Goods> killGoods = goodsService.getKillGoods();
        boolean timeToKill = goodsService.checkKillTime();
        Map<String, Object> map = new HashMap<>();
        map.put("killGoods",killGoods);
        map.put("timeToKill",timeToKill);
        return Result.success(map, killGoods.size());
    }

    @PostMapping("getTotalPrice")
    public Result getTotalPrice(@RequestBody GoodsDTO goodsDTO){
        List<OrderGoods> goodsList = goodsDTO.getGoodsList();
        double totalPrice = goodsService.getTotalPrice(goodsList);
        return Result.success(totalPrice);
    }


}
